package com.apple.reveal.controller.api;

import java.security.Key;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import com.apple.reveal.SessionConstant;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@Controller
public class UserApiController implements SessionConstant {
	
	@Autowired
	RequestMappingHandlerAdapter requestMappingHandlerAdapter;

	@RequestMapping(value = "/logon", method = RequestMethod.GET)
	public @ResponseBody String logon(HttpServletRequest request, HttpServletResponse response) {

		// HttpSession session=request.getSession(true);
		// session.setAttribute(SESSION_KEY_USER, "张三");

		return "success";
	}

	@RequestMapping(value = "query")
	public @ResponseBody QueryRequest query( QueryRequest reuqet) {

		System.out.println(requestMappingHandlerAdapter.getMessageConverters());
		System.out.println(reuqet);
		return reuqet;
	}

	/*@RequestMapping(value = "query", method = { RequestMethod.OPTIONS })
	public void query2(HttpServletRequest req, HttpServletResponse response) {

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET,OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", "session.create");

		System.out.println("options被请求了");

	}*/

	public static String getJWTString(String tel, Date expires, Key key) {
		if (tel == null) {
			throw new NullPointerException("null username is illegal");
		}

		if (expires == null) {
			throw new NullPointerException("null expires is illegal");
		}
		if (key == null) {
			throw new NullPointerException("null key is illegal");
		}
		// 用签名算法HS256和私钥key生成token
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		String jwtString = Jwts.builder().setIssuer("Jersey-Security-Basic")// 设置发行人
				.setSubject(tel)// 设置抽象主题
				.setAudience("user")// 设置角色
				.setExpiration(expires)// 过期时间
				.setIssuedAt(new Date())// 设置发行时间
				.setId("1")// 版本1
				.signWith(signatureAlgorithm, key).compact();
		return jwtString;
	}

}
